package com.itheima.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class ExceptionGlobalHandler {
    //捕获异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R sqlExec(SQLIntegrityConstraintViolationException e){
        e.printStackTrace();
        String message = e.getMessage();
        if(message.contains("idx_username")){
            String[] strings = message.split(" ");
            message = "用户名'"+strings[2]+"'已注册";
        }
        if(message.contains("idx_category_name")){
            String[] strings = message.split(" ");
            message = "分类'"+strings[2]+"'已存在";
        }
        return R.error(message);
    }
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
